﻿using ChartAI.DTO.CzRecord;
using ChartAI.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.LinqBuilder;
using ChartAI.Core.CM;

namespace ChartAI.Application.CzRecord.Services
{
    public class CzRecordServiceDM : ICzRecordServiceDM, ITransient
    {
        ISqlSugarClient c;
        public CzRecordServiceDM(ISqlSugarClient db)
        {
            c = db;
        }
        public ResultPageEntity<CzRecordDTO> GetCzRecordList(Request_CzRecord dto)
        {

            int count = 0;
            var query = c.Queryable<ChartAI_CzRecord, ChartAI_Users>((a, b) => a.UserId == b.Id)
               .WhereIF(!dto.UserName.IsNullOrEmpty(), (a, b) => b.UserName == dto.UserName)
               .WhereIF(!dto.Phone.IsNullOrEmpty(), (a, b) => b.Phone == Convert.ToInt32(dto.Phone))
               .WhereIF(!dto.AppId.IsNullOrEmpty(), (a, b) => b.AppId == dto.AppId)
               .WhereIF(!dto.FId.IsNullOrEmpty(), (a, b) => b.FId == Guid.Parse(dto.FId))
                .OrderByDescending(px => px.AddTime).ToPageList(dto.PageIndex, dto.PageSize, ref count);
            var list = query.Adapt<List<CzRecordDTO>>();
            return new ResultPageEntity<CzRecordDTO>() { Data = list, PageIndex = dto.PageIndex, PageSize = dto.PageSize, Count = count };
        }

        public ResultEntity<bool> AddCzRecord(CzRecordModel model)
        {

            ChartAI_CzRecord data = model.Adapt<ChartAI_CzRecord>();

            data.Id = Guid.NewGuid();

            data.AddTime = DateTime.Now;
            var result = c.Insertable(data).ExecuteCommand();
            if (result > 0)
            {
                var user = c.Queryable<ChartAI_Users>().InSingle(model.UserId);

                var czinfo = c.Queryable<ChartAI_CzInfo>().Where(w => w.Money == model.Money).First();
                czinfo.Number += czinfo.Number;

                c.Updateable(czinfo).ExecuteCommand();

                return new ResultEntityUtil<bool>().Success(true);

            }
            else
            {
                return new ResultEntityUtil<bool>().Success(false);
            }
        }

    }
}
